package com.lock.springbootdistributedlock.service;

import com.lock.springbootdistributedlock.annotation.DistributedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Service
public class OrderService {

    private final RedissonClient redissonClient;

    public OrderService(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 处理订单
     * @param orderId 订单ID
     */
    public void processOrder(String orderId) {
        RLock lock = redissonClient.getLock("order_lock:" + orderId);
        try {
            // 尝试获取锁，等待时间10秒，锁定时间30秒
            boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
            if (isLocked) {
                // 执行业务逻辑
                System.out.println("Processing order: " + orderId);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @DistributedLock(key = "order_lock_#{#orderId}")
    public void processOrderInfo(String orderId, BigDecimal amount) {
        // 处理订单信息逻辑
    }
}

